package cn.school.controller.educational;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.TeachingMaterial;
import cn.school.educational.entity.TeachingMaterialCollect;
import cn.school.educational.entity.TeachingMaterialStoreDetils;
import cn.school.educational.service.TeachingMaterialCollectService;
import cn.school.educational.service.TeachingMaterialService;
import cn.school.educational.service.TeachingMaterialStoreDetilsService;
import cn.school.sys.entity.SysUserRole;
import cn.school.sys.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @className: TeachingMaterialCollectController
 * @author: fangjin.tao
 * @date: 2022/12/9
 **/
@RestController
@Api(tags = "TeachingMaterialCollectController => 教领用管理")
@RequestMapping("/educational/teachingMaterialCollect")
public class TeachingMaterialCollectController {
	@Autowired
	private TeachingMaterialCollectService teachingMaterialCollectService;
	@Autowired
	private TeachingMaterialService teachingMaterialService;
	@Autowired
	private TeachingMaterialStoreDetilsService teachingMaterialStoreDetilsService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@ApiOperation("获取列表")
	@GetMapping("/list")
	public CommonResult<CommonPage<TeachingMaterialCollect>> list(@RequestParam Map<String, Object> para) {
		// 条件获取
		int pageNum = Integer.parseInt((String) para.get("pageNum"));
		int pageSize = Integer.parseInt((String) para.get("pageSize"));
		
		String tmcoCollectTime = (String) para.get("tmcoCollectTime"); // 领用日期
		String tmcoBeginCollectTime = (String) para.get("tmcoCollectTime"); // 领用查询-领用时间-左区间（开始）
		String tmcoEndCollectTime = (String) para.get("tmcoEndCollectTime"); // 领用查询-领用时间-右区间（结束）
		String temaId = (String) para.get("temaId"); // 教材ID
		String temaName = (String) para.get("temaName"); // 教材名称
		String tmsdCollectUserName = (String) para.get("tmsdCollectUserName"); // 申领人
		String tmsdCollectStatus = (String) para.get("tmsdCollectStatus"); // 申领状态
		String tmsdExamineUserName = (String) para.get("tmsdExamineUserName"); // 申审人
		
		
		Page<TeachingMaterialCollect> page = new Page<>();
		page.setSize(pageSize);
		page.setCurrent(pageNum);
		
		// queryWrapper查询设置
		LambdaQueryWrapper<TeachingMaterialCollect> queryWrapper = new LambdaQueryWrapper<>();
		//租户条件
		queryWrapper.eq(TeachingMaterialCollect::getTenantId, SysUserUtils.getSysUser().getTenantId());
		if (StrUtil.isNotEmpty(temaId)) {
			queryWrapper.eq(TeachingMaterialCollect::getTemaId, temaId);
		}
		if (StrUtil.isNotEmpty(tmcoCollectTime)) {
			// 具体日期
			queryWrapper.ge(TeachingMaterialCollect::getTmcoCollectTime, DateUtil.parse(tmcoCollectTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			queryWrapper.le(TeachingMaterialCollect::getTmcoCollectTime, DateUtil.parse(tmcoCollectTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(tmcoBeginCollectTime)) {
			queryWrapper.ge(TeachingMaterialCollect::getTmcoCollectTime, DateUtil.parse(tmcoBeginCollectTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(tmcoEndCollectTime)) {
			queryWrapper.le(TeachingMaterialCollect::getTmcoCollectTime, DateUtil.parse(tmcoEndCollectTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(temaName)) {
			queryWrapper.like(TeachingMaterialCollect::getTemaName, temaName);
		}
		if (StrUtil.isNotEmpty(tmsdCollectUserName)) {
			queryWrapper.like(TeachingMaterialCollect::getTmsdCollectUserName, tmsdCollectUserName);
		}
		if (StrUtil.isNotEmpty(tmsdCollectStatus)) {
			queryWrapper.eq(TeachingMaterialCollect::getTmsdCollectStatus, tmsdCollectStatus);
		}
		if (StrUtil.isNotEmpty(tmsdExamineUserName)) {
			queryWrapper.like(TeachingMaterialCollect::getTmsdCollectUserId, tmsdExamineUserName);
		}
		
		// 查询
		queryWrapper.orderByAsc(TeachingMaterialCollect::getTmsdCollectStatus);
		queryWrapper.orderByDesc(TeachingMaterialCollect::getTmcoCollectTime);
		IPage<TeachingMaterialCollect> iPage = this.teachingMaterialCollectService.page(page, queryWrapper);
		
		// 判断教务角色的ID，加上按钮展示字段
		if (iPage.getRecords() != null && iPage.getRecords().size() != 0) {
			LambdaQueryWrapper<SysUserRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
			roleLambdaQueryWrapper.eq(SysUserRole::getUserId, SysUserUtils.getSysUser().getId());
			roleLambdaQueryWrapper.eq(SysUserRole::getRoleId, 5L);
			int countEducationalRole = this.sysUserRoleService.count(roleLambdaQueryWrapper);
			if (countEducationalRole != 0) {
				for (TeachingMaterialCollect record : iPage.getRecords()) {
					record.setExamineBtmRight(true);
				}
			}
		}
		
		return CommonResult.success(CommonPage.restPage(iPage));
	}
	
	
	@ApiOperation("获取教材领用详情")
	@GetMapping("/info/{id}")
	public CommonResult<TeachingMaterialCollect> getInfoById(@PathVariable Long id) {
		TeachingMaterialCollect teachingMaterialCollect = this.teachingMaterialCollectService.getById(id);
		if (teachingMaterialCollect == null) {
			throw new ApiException("领用记录不存在，请刷新页面");
		}
		return CommonResult.success(teachingMaterialCollect);
	}
	
	
	@ApiOperation("添加教材领用")
	@PostMapping("/add")
	@Transactional
	public CommonResult<TeachingMaterialCollect> add(@RequestBody TeachingMaterialCollect teachingMaterialCollect) {
		TeachingMaterial teachingMaterial = this.teachingMaterialService.getById(teachingMaterialCollect.getTemaId());
		if (teachingMaterial == null) {
			throw new ApiException("教材不存在，请刷新页面后重试");
		}
		if (teachingMaterial.getTemaStoreAmount() < teachingMaterialCollect.getTmcoCollectCount()) {
			throw new ApiException("教材库存不够");
		}
		teachingMaterialCollect.setTemaName(teachingMaterial.getTemaName());
		teachingMaterialCollect.setTemaCode(teachingMaterial.getTemaCode());
		teachingMaterialCollect.setTmcoCollectTime(Calendar.getInstance().getTime());
		teachingMaterialCollect.setTmsdCollectUserId(SysUserUtils.getSysUser().getId());
		if (StrUtil.isNotEmpty(SysUserUtils.getSysUser().getSysuName())) {
			teachingMaterialCollect.setTmsdCollectUserName(SysUserUtils.getSysUser().getSysuName());
		} else {
			teachingMaterialCollect.setTmsdCollectUserName(SysUserUtils.getSysUser().getUsername());
		}
		teachingMaterialCollect.setTmsdCollectStatus("0");
		
		
		teachingMaterialCollect.setCreateTime(Calendar.getInstance().getTime());
		teachingMaterialCollect.setModifyTime(Calendar.getInstance().getTime());
		teachingMaterialCollect.setCreateBy(SysUserUtils.getSysUser().getId());
		
		boolean isAddSuccess = this.teachingMaterialCollectService.save(teachingMaterialCollect);
		if (isAddSuccess) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}
	
	@ApiOperation("审核教材领用")
	@PutMapping("/examine/{id}")
	public CommonResult<TeachingMaterialCollect> update(@PathVariable Long id, @RequestBody TeachingMaterialCollect teachingMaterialCollect) {
		TeachingMaterialCollect dbTmcoEntity = this.teachingMaterialCollectService.getById(id);
		if (dbTmcoEntity == null) {
			throw new ApiException("申领记录不存在，请刷新后重试");
		}
		if (!"0".equals(dbTmcoEntity.getTmsdCollectStatus())) {
			throw new ApiException("申领记录审核不能重复处理，请刷新界面");
		}
		dbTmcoEntity.setTmsdCollectStatus(teachingMaterialCollect.getTmsdCollectStatus());
		if ("1".equals(dbTmcoEntity.getTmsdCollectStatus())) {
			// 审核通过，检查库存数量
			TeachingMaterial teachingMaterial = this.teachingMaterialService.getById(teachingMaterialCollect.getTemaId());
			if (teachingMaterial == null) {
				throw new ApiException("教材不存在，请刷新页面后重试");
			}
			if (teachingMaterial.getTemaStoreAmount() < teachingMaterialCollect.getTmcoCollectCount()) {
				throw new ApiException("教材库存不够");
			}
			// 更新库存
			TeachingMaterialStoreDetils teachingMaterialStoreDetils = new TeachingMaterialStoreDetils();
			teachingMaterialStoreDetils.setTemaCode(teachingMaterial.getTemaCode());
			teachingMaterialStoreDetils.setTemaName(teachingMaterial.getTemaName());
			teachingMaterialStoreDetils.setTemaId(teachingMaterial.getId());
			teachingMaterialStoreDetils.setTmsdType("0"); //领取出库
			teachingMaterialStoreDetils.setTmsdCount(dbTmcoEntity.getTmcoCollectCount());
			
			// 保存领取记录
			teachingMaterialStoreDetils.setCreateBy(SysUserUtils.getSysUser().getId());
			teachingMaterialStoreDetils.setCreateTime(Calendar.getInstance().getTime());
			teachingMaterialStoreDetils.setModifyTime(Calendar.getInstance().getTime());
			this.teachingMaterialStoreDetilsService.saveBiz(teachingMaterialStoreDetils);
			teachingMaterialCollect.setTmsdId(teachingMaterialStoreDetils.getId());// 库存明细ID
		} else {
			// 不通过时，不做库存操作
		}
		teachingMaterialCollect.setTmsdExamineTime(Calendar.getInstance().getTime());
		teachingMaterialCollect.setTmsdExamineUserId(SysUserUtils.getSysUser().getId());
		if (StrUtil.isNotEmpty(SysUserUtils.getSysUser().getSysuName())) {
			teachingMaterialCollect.setTmsdExamineUserName(SysUserUtils.getSysUser().getSysuName());
		} else {
			teachingMaterialCollect.setTmsdExamineUserName(SysUserUtils.getSysUser().getUsername());
		}
		
		boolean isUpdateSuccess = this.teachingMaterialCollectService.updateById(teachingMaterialCollect);
		if (isUpdateSuccess) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}
	
	@ApiOperation("教材选择列表")
	@GetMapping("/teachingMaterial/list")
	public CommonResult<List<TeachingMaterial>> teachingMaterialList(Map<String, Object> params) {
		String queryTemaCodeOrName = (String) params.get("queryTemaCodeOrName");
		LambdaQueryWrapper<TeachingMaterial> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TeachingMaterial::getTenantId, SysUserUtils.getSysUser().getTenantId());
		if (StrUtil.isNotEmpty(queryTemaCodeOrName)) {
			queryWrapper.and((wrapper) -> {
				wrapper.like(TeachingMaterial::getTemaName, queryTemaCodeOrName.trim());
				wrapper.or().like(TeachingMaterial::getTemaCode, queryTemaCodeOrName.trim());
			});
		}
		List<TeachingMaterial> teachingMaterialList = this.teachingMaterialService.list(queryWrapper);
		return CommonResult.success(teachingMaterialList);
	}


//	@ApiOperation("删除领用明细")
//	@DeleteMapping("/deleteByIds/{ids}")
//	public CommonResult<TeachingMaterialCollect> delete(@PathVariable Long[] ids) {
//		List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
//		boolean isDeleteSuccess = this.teachingMaterialCollectService.removeByIds(idList);
//		if (isDeleteSuccess) {
//			return CommonResult.success();
//		} else {
//			return CommonResult.failed();
//		}
//	}
	
}
